package com.bflow.util;

import com.bflow.commons.util.StrUtil;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * @Name XXX
 * @Author haowen
 * @Date 2018/12/13
 */
public class SysSeqUtil {

    private static final Logger logger = LoggerFactory.getLogger(SysSeqUtil.class);

    private static Snowflake snowflake = new Snowflake(1);

    //增长数
    public static final int step = 1;

    /**
     * 生成ID
     * @return 19位长度数字
     */
    public static Long generateId() {
        return snowflake.nextId();
    }

    public static String[] CHARS = new String[] { "a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z" };


    public static String genId() {
        return genShortUUID();
    }

    public static String genShortUUID() {
        StringBuffer uuid = new StringBuffer(32);
        char[] chars = UUID.randomUUID().toString().toCharArray();
        for (char c : chars) {
            if(c != '-')
                uuid.append(c);
        }
        StringBuffer uuidShort = new StringBuffer(8);
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            uuidShort.append(CHARS[x % 0x3E]);
        }
        return uuidShort.toString().toUpperCase()+ RandomUtil.randomString(5).toUpperCase();
    }

    public static String toIntIdStr(Object id, int maxLen) {
        Integer num = 1;
        if(id != null && NumberUtils.isDigits(id.toString()))
            num = Integer.parseInt(id.toString()) + step;
        return StrUtil.numberFillZore(num, maxLen);
    }

    public static void main(String[] args) {
        Set<String> set = null;
        for (int j = 0; j < 1000; j++) {
            set = new HashSet<>();
            for(int i = 0; i < 2000; ++i) {
//                System.out.println(UUIDUtil.uuid());
//                System.out.println(snowflake.nextId());
//                System.out.println(genShortUUID());
                set.add(genShortUUID());
            }
            if(200000 != set.size())
                System.out.println(j+"-----"+set.size());
        }
    }


}
